package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Description:
 * @Version: V1.0
 */
@RestController
@RequestMapping("file")
public class FileController {
    @PostMapping("/upload")
    public Result uploudFile(MultipartFile file){
        try {
            //判断文件是否存在
            if (file==null){
                throw new RuntimeException("文件不存在");
            }
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)){
                throw new RuntimeException("文件不存在");
            }
            String estName = originalFilename.substring(originalFilename.lastIndexOf("." )+ 1);
            byte[] content = file.getBytes();
            FastDFSFile fastDFSFile=new FastDFSFile(originalFilename,content,estName);
            String[] uploadResult = FastDFSClient.upload(fastDFSFile);
            String url=FastDFSClient.getTrackerUrl()+uploadResult[0]+"/"+uploadResult[1];
            //System.out.println("============");
            System.out.println(url);
            return new Result(true,StatusCode.OK,"文件上传成功",url);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR,"文件上传 失败");
    }
}
